/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ouertech.android.agm.lib.base.constant.CstScheme;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilDevice;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Follow;
import com.simon.mengkou.data.bean.base.Image;
import com.simon.mengkou.data.bean.base.ImageExt;
import com.simon.mengkou.data.bean.base.ImageTag;
import com.simon.mengkou.data.bean.base.Tag;
import com.simon.mengkou.data.bean.req.ShareOrderAddReq;
import com.simon.mengkou.data.enums.EFileBelong;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.adapter.CreateImageAdapter;
import com.simon.mengkou.ui.base.BaseSelectImageActivity;
import com.simon.mengkou.ui.dialog.DeleteDialog;
import com.simon.mengkou.ui.view.MyGridView;
import com.simon.mengkou.ui.view.flowlayout.FlowLayout;
import com.simon.mengkou.utils.UtilOuer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/3/15.
 * desc    : 发布帖子界面
 */
public class CreateActivity extends BaseSelectImageActivity{
    //添加标签request code
    public static final int REQUEST_CODE_ADD_TAG = 100;
    //添加图片标签request code
    public static final int REQUEST_CODE_ADD_IMG_TAG = 101;
    //最多标签数
    private static final int MAX_TAGS = 10;
    //发布
    @Bind(R.id.create_id_post)
    Button mBtnPost;
    //发布
    @Bind(R.id.create_id_content)
    EditText mEtContent;
    //标签
    @Bind(R.id.create_id_tags)
    FlowLayout mFlTags;
    //图片
    @Bind(R.id.create_id_grid)
    MyGridView mMgvImages;

    private List<Tag> mTags;
    private List<String> mImages;
    private CreateImageAdapter mAdapter;
    private HashMap<String, ArrayList<ImageTag>> mTagMap;
    private List<ImageExt> mImageExts;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mTagMap = new HashMap<>();
        mImageExts = new ArrayList<>();
    }

    @Override
    protected void initTop() {
        setTitle(R.string.create_title);
        setNavigation(R.drawable.common_ic_left_nav);
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_create);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);

        mAdapter = new CreateImageAdapter(this);
        mMgvImages.setAdapter(mAdapter);

        final int width = UtilDevice.getDevice(this).getWidth();
        final int height = (int)(56 * UtilDevice.getDevice(this).getDensity());

        mBtnPost.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Rect rect = new Rect();
                        mBtnPost.getWindowVisibleDisplayFrame(rect);
                        mBtnPost.layout(0,
                                rect.bottom - rect.top - 2 * height,
                                width,
                                rect.bottom - rect.top - height);
                    }
                });
    }

    @OnClick(R.id.create_id_add_tag)
    public void searchTag() {
        OuerDispatcher.presentSearchTagActivity(this, REQUEST_CODE_ADD_TAG);
    }


    /**
     * 添加图片
     */
    public void selectPicture() {
        selectPicture(mMgvImages);
    }

    @Override
    public void onPhotoCropped(Uri uri) {
        super.onPhotoCropped(uri);
        if(uri != null) {
            String url = uri.toString();
            String path = url.replace(CstScheme.FILE, "");


            OuerDispatcher.presentImageTagEditActivity(this, path, REQUEST_CODE_ADD_IMG_TAG);

            boolean flag = false;
            if(mImages == null) {
                mImages = new ArrayList<>();
            }

            for(String img : mImages) {
                if(img.equals(path)) {
                    flag = true;
                    break;
                }
            }

            if(flag) {
                UtilOuer.toast(this, R.string.create_multiple_image);
            } else {
                mImages.add(path);
                mAdapter.setList(mImages);
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取添加的标签
        if(resultCode == RESULT_OK && requestCode == REQUEST_CODE_ADD_TAG) {
            ArrayList<Tag> tags = (ArrayList<Tag>) data.getSerializableExtra(CstOuer.KEY.TAGS);
            if(UtilList.isNotEmpty(tags)) {
                if(mTags == null) {
                    mTags = new ArrayList<>();
                }

                for(Tag tag : tags) {
                    boolean flag = false;
                    for(Tag t : mTags) {
                        if(t.getName().equals(tag.getName())) {
                            flag = true;
                            break;
                        }
                    }

                    if(!flag && UtilList.getCount(mTags)<MAX_TAGS) {
                        mTags.add(tag);
                    }
                }

                addTags();
            }
        } else if(resultCode == RESULT_OK && requestCode == REQUEST_CODE_ADD_IMG_TAG) {
            String path = data.getStringExtra(CstOuer.KEY.PATH);
            ArrayList<ImageTag> tags = (ArrayList<ImageTag>) data.getSerializableExtra(CstOuer.KEY.TAGS);
            mTagMap.put(path, tags);
        }
    }


    /**
     * 添加标签
     */
    private void addTags() {
        mFlTags.removeAllViews();
        if(UtilList.isNotEmpty(mTags)) {
            mFlTags.setVisibility(View.VISIBLE);
            for(final Tag tag : mTags) {
                TextView tvTag = new TextView(this);
                tvTag.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                tvTag.setBackgroundResource(R.drawable.share_order_ic_tag);
                tvTag.setSingleLine(true);
                tvTag.setEllipsize(TextUtils.TruncateAt.END);
                tvTag.setText(tag.getName());
                mFlTags.addView(tvTag);

                tvTag.setOnClickListener(new View.OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        final DeleteDialog dialog = new DeleteDialog(CreateActivity.this, null);
                        dialog.setOnClickListener(
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if(v.getId() == R.id.delete_id_delete) {
                                            mTags.remove(tag);
                                            addTags();
                                            dialog.dismiss();
                                        }
                                    }
                                });

                        dialog.showAtLocation(mFlTags, Gravity.CENTER, 0, 0);
                    }
                });
            }
        } else {
            mFlTags.setVisibility(View.GONE);
        }
    }


//    private void uploadImages() {
//        AgnettyFuture future = new OuerApplication().mOuerFuture.uploadImages(
//                mImages, EFileBelong.PRODUCT,
//                new OuerFutureListener(this) {
//                    public void onStart(AgnettyResult result) {
//                        setWaitingDialog(true);
//                    }
//
//                    @Override
//                    public void onComplete(AgnettyResult result) {
//                        super.onComplete(result);
//                        List<Image> images = (List<Image>) result.getAttach();
//
//                        if(UtilList.isEmpty(images)) {
//                            setWaitingDialog(false);
//                            UtilOuer.toast(CreateActivity.this, R.string.create_failure);
//                        } else {
//                            shareOrderAdd(images);
//                        }
//                    }
//
//                    public void onNetUnavaiable(AgnettyResult result) {
//                        super.onNetUnavaiable(result);
//                        setWaitingDialog(false);
//                    }
//
//                    @Override
//                    public void onException(AgnettyResult result) {
//                        super.onException(result);
//                        setWaitingDialog(false);
//                        UtilOuer.toast(CreateActivity.this, R.string.create_failure);
//                    }
//                });
//
//        attachDestroyFutures(future);
//    }


    private void uploadImages2(final List<String> images) {
        if(UtilList.isEmpty(images)) {
            if(UtilList.isEmpty(mImageExts)) {
                setWaitingDialog(false);
                UtilOuer.toast(CreateActivity.this, R.string.create_failure);
            } else {
                shareOrderAdd(mImageExts);
            }

            return;
        }

        final List<String> data = new ArrayList<>();
        data.add(images.get(0));
        images.remove(0);

        AgnettyFuture future = new OuerApplication().mOuerFuture.uploadImages(
                data, EFileBelong.PRODUCT,
                new OuerFutureListener(this) {

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        List<Image> datas = (List<Image>) result.getAttach();
                        ImageExt ext = new ImageExt();
                        ext.setKey(datas.get(0).getKey());
                        ext.setProperty(mTagMap.get(data.get(0)));
                        mImageExts.add(ext);
                        uploadImages2(images);
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        uploadImages2(images);
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        uploadImages2(images);
                    }
                });

        attachDestroyFutures(future);
    }

    private void shareOrderAdd(List<ImageExt> images) {
        //内容
        String content = mEtContent.getText().toString().trim();

        ShareOrderAddReq req = new ShareOrderAddReq();
        req.setUid(OuerApplication.mUser.getUserId());
        req.setContent(content);
        req.setImagesExt(images);
        req.setTags(mTags);

        AgnettyFuture future = OuerApplication.mOuerFuture.shareOrderAdd(req,
                new OuerFutureListener(this){

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setWaitingDialog(false);
                        Follow data = (Follow) result.getAttach();
                        UtilOuer.toast(CreateActivity.this, R.string.create_success);
                        //OuerDispatcher.sendMainTabChangedBroadcast(CreateActivity.this, 0);
                        OuerDispatcher.presentShareOrderDetailActivity(CreateActivity.this, data.getId());
                        finish();
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setWaitingDialog(false);
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setWaitingDialog(false);
                        //UtilOuer.toast(CreateActivity.this, R.string.create_failure);
                        UtilOuer.showExceptionToast(CreateActivity.this, result, R.string.create_failure);

                    }
                });

        attachDestroyFutures(future);
    }

    /**
     * 发布
     */
    @OnClick(R.id.create_id_post)
    public void post() {
        //添加图片
        if(UtilList.isEmpty(mImages)) {
            UtilOuer.toast(this, R.string.create_images_empty);
            return;
        }

        //添加标签
        if(UtilList.isEmpty(mTags)) {
            UtilOuer.toast(this, R.string.create_tags_empty);
            return;
        }

        List<String> images = new ArrayList<>();
        for(String str : mImages) {
            images.add(str);
        }

        setWaitingDialog(true);
        uploadImages2(images);
    }



}
